Linked List Random Node
Question
Given a singly linked list, return a random node’s value from the linked list. Each node must have the same probability of being chosen.
Follow up:
What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?
Example:
|
|
Analysis
朴素做法是遍历数组得到len后,根据len生成随机数从中任取一个,即每个节点被选择的概率都相同。但是follow up中提示链表的长度未知,可能很长,所以利用水塘抽样即可在遍历的同时以均等的概率选取节点。
Code
|
|
Random Pick Index
Question
Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.
Note:
The array size can be very large. Solution that uses too much extra space will not pass the judge.
Example:
|
|
Analysis
Code
|
|